using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Xml.Serialization;
using MaxAlarm.Common;

namespace MaxAlarm.Core.Settings
{
    public class AlarmSettings : DependencyObject, ICloneable
    {
        public static readonly DependencyProperty ItemsProperty =
            DependencyProperty.Register("Items", typeof(ObservableCollection<AlarmSettingsItem>), typeof(AlarmSettings), new PropertyMetadata(null));

        [XmlElement("alarm")]
        public ObservableCollection<AlarmSettingsItem> Items
        {
            get { return this.SafeGetValue<ObservableCollection<AlarmSettingsItem>>(ItemsProperty); }
            set { this.SafeSetValue(ItemsProperty, value); }
        }

        public void AddNew(string type, AlarmAction action = AlarmAction.Ignore, AlarmLevel level = AlarmLevel.Info, int waitInterval = 0)
        {
            AddNew(new AlarmSettingsItem{Action = action, Level = level, Type = type.Trim(), WaitInterval = waitInterval});
        }

        public void AddNew(AlarmSettingsItem item)
        {
            if (string.IsNullOrEmpty(item.Type) || string.IsNullOrEmpty(item.Type.Trim()))
                throw new ArgumentException("Alarm type is empty!");

            if (!AlreadyExists(item.Type))
            {
                Items.Add(item);
                return;
            }

            var index = Items.IndexOf(Items.Where(e=>e.Type == item.Type).First());
            Items[index] = item;
        }

        public bool AlreadyExists(string type)
        {
            return Items.Any(e => e.Type.ToUpper() == type.ToUpper().Trim());
        }

        public AlarmSettings()
        {
            Items = new ObservableCollection<AlarmSettingsItem>();
        }

        public object Clone()
        {
            return new AlarmSettings {Items = new ObservableCollection<AlarmSettingsItem>(Items)};
        }

        public AlarmSettingsItem this[string type]
        {
            get 
            { 
                var item = Items.Where(e => e.Type == type).First();
                return item ?? new AlarmSettingsItem(type);
            }
        }
    }
}
